package com.fzj.example.socket.tcp.nonblock.aio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * ClassName: AioClient
 * date: 2019/11/21 14:58
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class AioClient {

    private static Charset charset = Charset.forName("US-ASCII");

    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
        AsynchronousSocketChannel asc=AsynchronousSocketChannel.open();
        Future<Void> f=asc.connect(new InetSocketAddress(InetAddress.getByName("192.168.0.23"),9932));
        f.get();
        ByteBuffer buffer = ByteBuffer.allocate(100);
        asc.read(buffer, null, new CompletionHandler<Integer, Void>() {
            @Override
            public void completed(Integer result, Void attachment) {
                System.out.println(result);
                System.out.println("client received: " + new String(buffer.array(),0,result));

            }
            @Override
            public void failed(Throwable exc, Void attachment) {
                exc.printStackTrace();
                try {
                    asc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        Thread.sleep(10000);
    }
}
